package xl.com.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xl.com.model.*;

import java.io.IOException;
import java.util.List;

// 步骤3：实现DeepSeek客户端
@Service
@RequiredArgsConstructor
public class DeepSeekClient {
    @Autowired
    private final OkHttpClient httpClient;

    private static final String API_URL = "https://openapi.coreshub.cn/v1/chat/completions";

    private String apiKey="sk-XB5Bxk5CWZLHTguXsH4q72MT4YULhKQGewgRVrKejOvyxx4O";
    private String chatModel="DeepSeek-V3";
    public Choice callChatAPI(List<XlMessage> messages, XLFunction functions) {
        try {
            // 构建请求体
            ChatRequest request = new ChatRequest(
                    chatModel,
                    messages,
                    List.of(functions),
                    0.7
                    ,"auto"
            );


            // 发送请求并处理响应（实际实现需要处理异常和错误码）
            RequestBody body = RequestBody.create(
                    new ObjectMapper().writeValueAsString(request),
                    MediaType.get("application/json")
            );

            Request httpRequest = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .build();

            try (Response response = httpClient.newCall(httpRequest).execute()) {
                String string = response.body().string();
                ChatResponse resp = new ObjectMapper()
                        .readValue(string, ChatResponse.class);
                return resp.getChoices().get(0);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
